package com.xxx.mall.api;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.xxx.mall.config.MinioTemplate;
import com.xxx.mall.config.OssConfig;
import com.xxx.mall.response.R;
import com.xxx.mall.vo.OssVO;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 邢晨旭
 * {@code @date} 2023/11/20
 */
@RestController
@RequestMapping("/oss")
public class OssApi {

    private static final String NORM_DAY_PATTERN = "/yyyy/MM/dd/";

    @Resource
    MinioTemplate minioTemplate;

    @PostMapping("/upload_minio")
    public R<OssVO> uploadMinio(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return R.err("文件为空");
        }
        OssVO ossVO = new OssVO();
        ossVO.setDir(DateUtil.format(new Date(), NORM_DAY_PATTERN));
        ossVO.setFileName(IdUtil.fastSimpleUUID());
        minioTemplate.uploadMinio(file.getBytes(), ossVO.getDir() + ossVO.getFileName(), file.getContentType());
        return R.ok(ossVO);
    }

    @GetMapping("/info")
    public R<List<OssVO>> info(@RequestParam("fileNum") Integer fileNum) {
        ArrayList<OssVO> list = new ArrayList<>();
        for (int i = 0; i < fileNum; i++) {
            OssVO ossVO = new OssVO();
            ossVO.setDir(DateUtil.format(new Date(), NORM_DAY_PATTERN));
            ossVO.setFileName(IdUtil.fastSimpleUUID());
            ossVO.setActionUrl(minioTemplate.getPresignedObjectUrl(ossVO.getDir() + ossVO.getFileName()));
            list.add(ossVO);
        }
        return R.ok(list);
    }

}
